﻿var livetv = function ($) {
    var settings = {
        duration: 10000,
        containerElement: '#liveTvContainer',
        contentPlaceHolderElement: "#liveTvContainer .livetv table:first",
        requestUrl: "/Services/News/GetLiveNews.ashx"
    };

    var closestItemId = 0;
    var liveStatus = false;

    function execCallback(callback) {
        if (typeof callback == "function") {
            return callback();
        }
        return false;
    }
    function loadData(newsId, callback) {
        $.ajax({
            url: settings.requestUrl,
            data: { newsId: newsId, closestItemId: closestItemId },
            dataType: 'json',
            success: function (response) {
                if (response.Success) {
                    bindData(response.Data);
                    execCallback(callback);
                }
            }
        });
    }

    function bindData(json) {
        if (json && json.length > 0) {
            var html = '';
            var hliClass = String.format("liveTvItem_{0}", closestItemId);
            var format = "<tr class='{2}'><th><p class=\"inner\">{0}</p></th><td><div class=\"inner\">{1}</div></td></tr>";
            for (var i = 0; i < json.length; i++) {
                var item = json[i];
                if (item.Id > closestItemId) {
                    closestItemId = item.Id;
                }
                html += String.format(format, item.PublishedDate, item.Content, hliClass);
            }
            if ($(settings.contentPlaceHolderElement).find('tr').length > 0) {
                $(settings.contentPlaceHolderElement).find('tr:first-child').before(html);
                $("." + hliClass).effect('highlight');
            } else {
                $(settings.contentPlaceHolderElement).html(html);
            }
            liveStatus = true;
            return true;
        }
        if (!liveStatus) {
            $(settings.containerElement).hide();
        }
        return false;
    }

    var liveTvInterval = undefined;
    function keeplive(newsId) {
        if (typeof liveTvInterval == "undefined") {
            liveTvInterval = setInterval(function () {
                loadData(newsId);
            }, settings.duration);
        }
    }

    return {
        reConfig: function (options) {
            $.extend(settings, options);
        },
        init: function (newsId) {
            $(settings.containerElement).hide();
            loadData(newsId, function () {
                keeplive(newsId);
                $(settings.containerElement).show();
            });
        }
    };
} (jQuery);